﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ProTrack.Api.Helper;
using ProTrack.Dto;
using ProTrack.Entity;
using ProTrack.IServices.Examine;
using ProTrack.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ProTrack.Api.Controllers
{
    /// <summary>
    /// 来料检验单控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class QcReceiveRecordController : ControllerBase
    {
        public QcReceiveRecordController(IQcReceiveRecordServices services, LogHelper LogHelper)
        {
            Services = services;
            this.LogHelper = LogHelper;
        }

        public IQcReceiveRecordServices Services { get; }
        public LogHelper LogHelper { get; }



        /// <summary>
        /// 获取所有来料检验单
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAll")]
        public async Task<IActionResult> GetAll()
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetAllAsync();
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("来料检验单-获取所有", ex, HttpContext);
            }


            return Ok(status);
        }


        /// <summary>
        /// 分页获取来料检验单
        /// </summary>
        /// <param name="PageIndex">当前页</param>
        /// <param name="PageSize">页大小</param>
        /// <param name="RecordCode">来料检验单编号</param>
        /// <param name="ItemName">商品名</param>
        /// <param name="Status">检验结果</param>
        /// <returns></returns>

        [HttpGet]
        public async Task<IActionResult> Get([FromQuery] int PageIndex, [FromQuery] int PageSize, [FromQuery] string RecordCode, [FromQuery] string ItemName, [FromQuery] string Status)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                RecordCode = RecordCode ?? "";
                ItemName = ItemName ?? "";
                Status = Status ?? "";

                var list = await Services.GetAsync(PageIndex, PageSize, RecordCode, ItemName, Status);
                status.Data = list;
                status.Count = await Services.GetCountAsync(RecordCode, ItemName, Status);
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("来料检验单-分页获取", ex, HttpContext);
            }

            return Ok(status);
        }



        /// <summary>
        /// 新增来料检验单
        /// </summary>
        /// <param name="model">来料检验单模型</param>
        /// <param name="QcReceiveRecordItemString">来料检验单子项 (选择检测项设置) 集合，使用字符串序列化数组</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add([FromForm] QcReceiveRecord model, [FromForm] string QcReceiveRecordItemString)
        {

            var status = BaseStatus.CreateInstance();
            List<QcReceiveRecordItemDto> list = new List<QcReceiveRecordItemDto>();
            try
            {
                //判断来料检验单子项是否有数据
                if (!string.IsNullOrEmpty(QcReceiveRecordItemString))
                {
                    list = JsonConvert.DeserializeObject<List<QcReceiveRecordItemDto>>(QcReceiveRecordItemString);
                    list.ForEach(x => {

                        //重新将编辑的主表信息 赋值给从表
                        x.RecordId = model.Id;


                    });
                }
                model.CreateTime = StringHelper.GetTimeNow();
                model.Creator = User.Identity.Name;
                var isSuccess = await Services.AddAsync(model, list);
                if (isSuccess)
                {
                    status.Msg = "新增成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "新增失败，请检查数据";
                }

            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("来料检验单-新增", ex, HttpContext);
            }
            return Ok(status);


        }

        /// <summary>
        /// 修改来料检验单
        /// </summary>
        /// <param name="model">来料检验单模型</param>
        /// <param name="QcReceiveRecordItemString">来料检验单子项 (选择检测项设置) 集合，使用字符串序列化数组</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Update([FromForm] QcReceiveRecord model, [FromForm] string QcReceiveRecordItemString)
        {

            var status = BaseStatus.CreateInstance();
            List<QcReceiveRecordItemDto> list = new List<QcReceiveRecordItemDto>();
            try
            {
                //判断来料检验单子项是否有数据
                if (!string.IsNullOrEmpty(QcReceiveRecordItemString))
                {
                    list = JsonConvert.DeserializeObject<List<QcReceiveRecordItemDto>>(QcReceiveRecordItemString);
                    list.ForEach(x => {

                        //重新将编辑的主表信息 赋值给从表
                        x.RecordId = model.Id;


                    });
                }
                model.UpdateTime = StringHelper.GetTimeNow();
                model.Updater = User.Identity.Name;
                var isSuccess = await Services.UpdateAsync(model, list);
                if (isSuccess)
                {
                    status.Msg = "修改成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "修改失败，请检查数据";
                }

            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("来料检验单-修改", ex, HttpContext);
            }
            return Ok(status);


        }


        /// <summary>
        /// 批量删除来料检验单
        /// </summary>
        /// <param name="Ids">料检验单Id数组</param>
        /// <returns></returns>
        [HttpDelete("DelAll")]
        public async Task<IActionResult> DelAll([FromForm] string Ids)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var arr = Ids.SplitId();
                var isSuccess = await Services.DeleteAsync(arr);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("来料检验单-批量删除", ex, HttpContext);
            }

            return Ok(status);
        }



        /// <summary>
        /// 删除来料检验单
        /// </summary>
        /// <param name="Id">料检验单Id</param>
        /// <returns></returns>
        [HttpDelete]

        public async Task<IActionResult> Del([FromForm] int Id)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var isSuccess = await Services.DeleteAsync(Id);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("来料检验单-删除", ex, HttpContext);
            }

            return Ok(status);
        }

        /// <summary>
        /// 根据到货通知单Id获取采购数据
        /// </summary>
        /// <param name="WareHouseInboundBillId">单据Id</param>
        /// <returns></returns>
        [HttpGet("GetItemByWareHouseInboundBillId")]
        public async Task<IActionResult> GetItemByWareHouseInboundBillId([FromQuery] string WareHouseInboundBillId)
         {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetItemByWareHouseInboundBillId(WareHouseInboundBillId);
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("来料检验-获取采购数据", ex, HttpContext);
            }
            return Ok(status);
        }



        /// <summary>
        /// 根据商品Id获取来料检验标准
        /// </summary>
        /// <param name="ItemId">商品Id</param>
        /// <returns></returns>
        [HttpGet("GetQcProcessStandardItemByItemId")]
        public async Task<IActionResult> GetQcProcessStandardItemByItemId([FromQuery] string ItemId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                
                var list = await Services.GetQcProcessStandardItemByItemId(ItemId);
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("来料检验-获取来料检验标准", ex, HttpContext);
            }

            return Ok(status);
        }


        /// <summary>
        /// 根据来料检验单Id获取来料检验单子项和缺陷记录明细
        /// </summary>
        /// <param name="QcReceiveRecordId">料检验单子项Id</param>
        /// <returns></returns>
        [HttpGet("GetQcReceiveRecordItemDetailsByQcReceiveRecordId")]
        public async Task<IActionResult> GetQcReceiveRecordItemDetailsByQcReceiveRecordId([FromQuery] string QcReceiveRecordId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {

                var list = await Services.GetQcReceiveRecordItemDetailsByQcReceiveRecordId(QcReceiveRecordId);
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("来料检验-获取来料检验单子项和缺陷记录明细", ex, HttpContext);
            }

            return Ok(status);
        }





        /// <summary>
        /// 修改单据状态
        /// </summary>
        /// <param name="Id">单据Id</param>
        /// <param name="Status">状态：0待审核 1已审核</param>
        /// <returns></returns>
        [HttpPut("UpdateStatus")]
        public async Task<IActionResult> UpdateStatus([FromForm] long Id, [FromForm] int Status)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.UpdateStatus(Id, Status);
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("来料检验-修改状态", ex, HttpContext);
            }
            return Ok(status);
        }




    }
}
